﻿using MediatR.Pipeline;
using MeetingRoomBooking.Application.Common.Interfaces;
using Microsoft.Extensions.Logging;

namespace MeetingRoomBooking.Application.Common.Behaviours;
public class LoggingRequestPreProcessor<TRequest> : IRequestPreProcessor<TRequest> where TRequest : notnull
{
    private readonly ILogger _logger;
    private readonly IUser _user;
    private readonly IApplicationDbContext _dbContext;

    public LoggingRequestPreProcessor(ILogger<TRequest> logger, IUser user, IApplicationDbContext dbContext)
    {
        _logger = logger;
        _user = user;
        _dbContext = dbContext;       
    }

    public async Task Process(TRequest request, CancellationToken cancellationToken)
    {
        var requestName = typeof(TRequest).Name;
        var userId = _user.Id ?? string.Empty;
        string? userName = string.Empty;

        if (!string.IsNullOrEmpty(userId))
        {
            var user = await _dbContext.Users.FindAsync(Convert.ToInt32(userId));
            userName = user?.UserName;
        }

        _logger.LogInformation("MeetingRoomBooking Request: {Name} {@UserId} {@UserName} {@Request}",
            requestName, userId, userName, request);
    }
}
